package com.hitqz.robot.driver.zmq.protocol.handler;

import com.example.tutorial.AddressBookProtos;
import com.hitqz.robot.driver.util.WheelCacheUtil;
import com.hitqz.robot.driver.util.WheelToolkit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.locks.Lock;

/**
 * 传感器避障信息处理类
 *
 * @author wengyx
 * @date 2021-09-14 17:12
 **/
@Slf4j
@Component
public class SensorHandler implements HandlerZMQService {

    @Override
    public void handlerMsg(String robotSn, byte[] data) throws Exception {
        AddressBookProtos.Sensor sensor = AddressBookProtos.Sensor.parseFrom(data);
        String type = sensor.getDescriptorForType().getName();
        int objId = sensor.getHeader().getObj();
        int ackId = sensor.getHeader().getAck();
        //由于目前不支持单个设置，所以数组数值应一致，以第一个为准
        HashMap<String, Integer> sensorMap = new HashMap<>();
        sensorMap.put("sonar", sensor.getSonarList().contains(1) ? 1 : 0);
        sensorMap.put("antiCollision", sensor.getAntiCollisionList().contains(1)  ? 1 : 0);
        sensorMap.put("avoidInfrared", sensor.getAvoidInfraredList().contains(1)  ? 1 : 0);
        sensorMap.put("avoidLidar", sensor.getAvoidLidarList().contains(1) ? 1 : 0);
        sensorMap.put("dropProof", sensor.getDropProofList().contains(1) ? 1 : 0);
        sensorMap.put("micrometerWaveLidar", sensor.getMicrometerWaveLidarList().contains(1)  ? 1 : 0);
        switch (objId) {
            //传感器避障状态上报
            case AddressBookProtos.Sensor.OBJ_ID.NUL_SENSOR_AVOID_STATUS_NTF_VALUE-> {
                Map<String, Integer> lastStatus = (Map<String, Integer>) WheelCacheUtil.get(WheelCacheUtil.KEY_SENSOR_STATUS);
                Integer lastSonar = Optional.ofNullable(lastStatus).map(map -> map.get("sonar")).orElse(0);
                WheelCacheUtil.put(WheelCacheUtil.KEY_SENSOR_STATUS,sensorMap);
                if (sensorMap.containsKey("sonar")) {
                    Integer sonar = sensorMap.get("sonar");
                    // 避免一直报警
                    if (sonar == 1 && !Objects.equals(lastSonar, sonar)) {
                        //todo 超声波告警
                    }
                }
            }
            //返回传感器避障使能状态
            case AddressBookProtos.Sensor.OBJ_ID.GET_SENSOR_AVOID_ENABLE_REP_VALUE->{
                WheelCacheUtil.put(WheelCacheUtil.KEY_SENSOR_ENABLE_STATUS,sensorMap);
            }

        }

        //释放锁
        WheelToolkit.release(ackId,type, objId, true);

    }



}
